﻿using System;
using System.Windows.Threading;

namespace Neudesic.Pulse.Extensions
{

    /// <summary>
    /// 
    /// </summary>
    public static class DispatcherObjectExtensions
    {
        /// <summary>
        /// Executes a function using thread affinity if needed.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="func">The func.</param>
        /// <returns></returns>
        public static TReturn Dispatch<T, TReturn>(this T source, Func<TReturn> func) where T : DispatcherObject
        {
            if (source.Dispatcher.CheckAccess())
                return func();

            return (TReturn)source.Dispatcher.Invoke(func);
        }

        /// <summary>
        /// Executes an action using thread affinity if needed.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="act">The act.</param>
        public static void Dispatch<T>(this T source, Action action) where T : DispatcherObject
        {
            if (source.Dispatcher.CheckAccess())
                action();
            else
                source.Dispatcher.Invoke(action);
        }

    }

}
